
goog.provide('esn.RandomFriendsSurvey');

goog.require('esn.BaseSurvey');
goog.require('esn.constants');
goog.require('esn.dao.FriendSurveyDao');
goog.require('esn.soy.randomFriendsSurvey');
goog.require('goog.array');
goog.require('goog.string');


/**
 * @constructor
 */
esn.RandomFriendsSurvey = function(appContext, opt_domHelper) {
  goog.base(this, appContext, esn.RandomFriendsSurvey.SECTION_ID, opt_domHelper);

  this.appContext_ = appContext;

  this.surveyClient_ = this.appContext_.getService(
      esn.constants.ServiceId.SURVEY_CLIENT);
};
goog.inherits(esn.RandomFriendsSurvey, esn.BaseSurvey);

esn.RandomFriendsSurvey.SECTION_ID = 'random_people';

esn.RandomFriendsSurvey.EventType = {
  BACK: goog.events.getUniqueId('back'),
  CONTINUE: goog.events.getUniqueId('continue')
};

esn.RandomFriendsSurvey.prototype.friendSurveys_;

esn.RandomFriendsSurvey.prototype.randomFriendSurveyDoas_;

esn.RandomFriendsSurvey.prototype.continueButton_;

esn.RandomFriendsSurvey.prototype.backButton_;

esn.RandomFriendsSurvey.prototype.setFriendSurveys = function(friendSurveys) {
  this.friendSurveys_ = friendSurveys;
  this.randomFriendSurveyDoas_ = this.getRandomFriendSurveyDoas_();
};

esn.RandomFriendsSurvey.prototype.enterDocument = function() {
  goog.base(this, 'enterDocument');

  var textareaEls = this.getElement().getElementsByTagName('textarea');
  goog.array.forEach(textareaEls, function(textareaEl) {
    this.getHandler().listen(
        textareaEl,
        goog.events.EventType.BLUR,
        this.handleInputChange_);
  }, this);

  this.getHandler().listen(
      this.continueButton_,
      goog.ui.Component.EventType.ACTION,
      this.handleContinueClick_);

  this.getHandler().listen(
      this.backButton_,
      goog.ui.Component.EventType.ACTION,
      this.handleBackClick_);
};

esn.RandomFriendsSurvey.prototype.createDom = function() {
  goog.base(this, 'createDom');

  if (!this.friendSurveys_) {
    throw new Error('Random friends survey cannot be rendered until friend ' +
        'surveys are set.');
  }

  // We need to convert random friends to JS objects for the soy template.
  var friendSurveyObjs = goog.array.map(this.randomFriendSurveyDoas_, function(
      friendSurveyDoa) {
    return friendSurveyDoa.getModel().toObject();
  });

  var tmplData = {
    FriendSurveys: friendSurveyObjs
  };
  this.setElementInternal(
      soy.renderAsElement(esn.soy.randomFriendsSurvey.content, tmplData));

  this.continueButton_ = new goog.ui.CustomButton('Finish Survey!');
  this.continueButton_.render(this.getElementByClass('continueButton'));

  this.backButton_ = new goog.ui.CustomButton(
      esn.constants.getBackButtonCaption());
  this.backButton_.render(this.getElementByClass('backButton'));

  // Call input handler to update progress bar.
  this.handleInputChange_();
};

esn.RandomFriendsSurvey.prototype.getRandomFriendSurveyDoas_ = function() {
  var randomFriendSurveys = [];
  if (this.friendSurveys_.length <= 1) {
    // This use has 1 or fewer friends so let's use them all.
    randomFriendSurveys = this.friendSurveys_;
  } else {
    // Check to see if this user already has randomly selected friends.
    randomFriendSurveys = goog.array.filter(this.friendSurveys_,
        function(friendSurvey) {
      return friendSurvey.isRandomFriend();
    });

    // Select random friends.
    while (randomFriendSurveys.length < 1) {
      var randIndex = Math.floor(Math.random() * this.friendSurveys_.length);
      var randomFriendSurvey = this.friendSurveys_[randIndex];
      if (!goog.array.contains(randomFriendSurveys, randomFriendSurvey)) {
        randomFriendSurveys.push(randomFriendSurvey);
      }
    }
  }

  // Create a DOA object for each randomly selected friend survey.
  return goog.array.map(randomFriendSurveys, function(friendSurvey) {
    var friendSurveyDoa =  new esn.dao.FriendSurveyDao(friendSurvey,
        this.surveyClient_);
    // Mark this user as a randomly selected friend and save the changes.
    var friendSurvey = friendSurveyDoa.getModel();
    if (!friendSurvey.isRandomFriend()) {
      friendSurvey.setIsRandomFriend(true);
      friendSurveyDoa.save();
    }
    return friendSurveyDoa;
  }, this);
};

esn.RandomFriendsSurvey.prototype.handleInputChange_ = function() {
  var textareaEls = this.getElement().getElementsByTagName('textarea');
  var completedEls = goog.array.filter(textareaEls, function(textareaEl) {
    return goog.string.trim(textareaEl.value) != '';
  });

  if (completedEls.length > 0) {
    var numQuestions = textareaEls.length * 10;
    var numAnswered = Math.floor(completedEls.length * 10 * 0.8);
    this.dispatchChangeEvent_(numQuestions, numAnswered);
  }
};

esn.RandomFriendsSurvey.prototype.handleContinueClick_ = function(e) {
  this.saveAnswers_();
  this.dispatchChangeEvent_(1, 1);
  this.dispatchEvent(esn.RandomFriendsSurvey.EventType.CONTINUE);
};

esn.RandomFriendsSurvey.prototype.saveAnswers_ = function() {
  goog.array.forEach(this.randomFriendSurveyDoas_, function(friendSurveyDoa) {
    var friendSurvey = friendSurveyDoa.getModel();
    var questionOneInput = goog.dom.getElement(friendSurvey.getId() +
        '-questionOneInput');
    var questionTwoInput = goog.dom.getElement(friendSurvey.getId() +
        '-questionTwoInput');
    friendSurvey.setFirstMetLocation(goog.string.trim(questionOneInput.value));
    friendSurvey.setFirstMetInteraction(
        goog.string.trim(questionTwoInput.value));
    friendSurveyDoa.save();
  }, this);
};

esn.RandomFriendsSurvey.prototype.handleBackClick_ = function(e) {
  this.dispatchEvent(esn.RandomFriendsSurvey.EventType.BACK);
};

/**
 * Dispatches change event to update progress bar.
 */
esn.RandomFriendsSurvey.prototype.dispatchChangeEvent_ = function(numQuestions,
    numAnswered) {
  this.dispatchEvent(new esn.BaseSurvey.ChangeEvent(
      esn.RandomFriendsSurvey.SECTION_ID, numQuestions, numAnswered));
};
